package com.weijing.pretty_app.util

object HexConverter {
    /**
     * 将字符串转换为十六进制字符串（UTF-8 编码）
     * 例如："Hi" -> "4869"
     */
    fun stringToHex(text: String): String {
        return text.encodeToByteArray().joinToString("") { "%02X".format(it) }
    }

    /**
     * "AA FF E7 03 01 00 8C EE" 变成 [AA, FF, E7, 03, 01, 00, 8C, EE]
     */
    fun stringToHexList(raw: String): List<String> {
        return raw.trim()
            .split("\\s+".toRegex()) // 按空格分割
            .map { it.uppercase() }  // 全部转大写，保持一致性
    }

    /**
     * [AA, FF, E7, 03, 01, 00, 8C, EE] 转 AA FF E7 03 01 00 8C EE
     */
    fun hexListToSpacedString(hexList: List<String>): String {
        return hexList.joinToString(" ")
    }

    /**
     * 将100转成hex 如：00 64
     * val hexBytes = intTo2ByteHex(100)
     * val hexString = hexBytes.joinToString(" ") { "%02X".format(it) }
     */
    fun intTo2ByteHex(value: Int): ByteArray {
        return byteArrayOf(
            ((value shr 8) and 0xFF).toByte(), // 高位
            (value and 0xFF).toByte()          // 低位
        )
    }

    /**
     * 不保留高位(支持负数)
     * 将100转成hex 如：64
     * val hexBytes = intTo2ByteHex(100)
     * val hexString = hexBytes.joinToString(" ") { "%02X".format(it) }
     */
    fun intTo1ByteHex(value: Int): ByteArray {
//        require(value in 0..255) { "Value must be between 0 and 255 to fit in 1 byte" }
        return byteArrayOf((value and 0xFF).toByte())
    }

    /**
     * 将十六进制字符串转换为普通字符串
     * 例如："4869" -> "Hi"
     */
    fun hexToString(hex: String): String {
        val bytes = hexToByteArray(hex)
        return bytes.toString(Charsets.UTF_8)
    }

    /**
     * 将 ByteArray 转换为十六进制字符串
     * 例如：[0x48, 0x69] -> "4869"
     */
    fun byteArrayToHex(data: ByteArray): String {
        return data.joinToString("") { "%02X".format(it) }
    }

    /**
     * 将十六进制字符串转换为 ByteArray
     * 例如："4869" -> [0x48, 0x69]
     */
    fun hexToByteArray(hex: String): ByteArray {
        val cleanHex = hex.replace(" ", "")
        require(cleanHex.length % 2 == 0) { "Hex string must have even length" }
        return ByteArray(cleanHex.length / 2) {
            cleanHex.substring(it * 2, it * 2 + 2).toInt(16).toByte()
        }
    }

    /**
     * 发送字符串
     * val hex = HexConverter.stringToHex("Hello")  // "48656C6C6F"
     * val bytes = HexConverter.hexToByteArray(hex)
     * BluetoothSPPManager.send(bytes)
     *
     * 接收
     * BluetoothSPPManager.addDataReceivedListener { data ->
     * val hex = HexConverter.byteArrayToHex(data)
     * val text = HexConverter.hexToString(hex)
     * Log.d("BluetoothReceiver", "HEX: $hex, TEXT: $text")
     * }
     */


    /**
     * 将形如 "AA 55 E3 02 01 01" 的十六进制字符串转换为 ByteArray
     */
    fun hexStringToByteArray(hexStr: String): ByteArray {
        val cleanHex = hexStr.replace(" ", "")
        require(cleanHex.length % 2 == 0) { "Invalid hex string length" }
        return ByteArray(cleanHex.length / 2) {
            cleanHex.substring(it * 2, it * 2 + 2).toInt(16).toByte()
        }
    }

    /**
     * 将 ByteArray 转换为十六进制字符串，比如 [0xAA, 0x55] -> "AA 55"
     */
    fun byteArrayToHexString(bytes: ByteArray): String {
        return bytes.joinToString(" ") { "%02X".format(it) }
    }

    /**
     * 数组转字符串
     * 原始数据: [02, 01, 00, 02, 03, 04, 05, 07, 08, 09]
     * 去掉 0 后: [2, 1, 2, 3, 4, 5, 7, 8, 9]
     * 拼接结果: "212345789"
     */
    fun filterAndJoinDigits(data: List<String>): String {
        return data.mapNotNull { it.toIntOrNull(16) } // 把 hex 字符串转换成 Int
            .filter { it != 0 }                       // 去掉等于 0 的值
            .joinToString("") { it.toString() }       // 拼接成字符串
    }
}

fun main() {
    val aaa = HexConverter.hexListToSpacedString(listOf("AA", "FF", "E7", "03", "01", "00", "8C", "EE"))
    println(aaa)
}